package com.betty.cscams.controller;

import com.betty.cscams.common.http.HttpResult;
import com.betty.cscams.constant.SysConstants;
import com.betty.cscams.entity.BusTerm;
import com.betty.cscams.entity.PsyAnswer;
import com.betty.cscams.entity.PsyQuestion;
import com.betty.cscams.service.BusTermService;
import com.betty.cscams.service.PsyAnswerService;
import com.betty.cscams.service.PsyQuestionService;
import com.betty.cscams.util.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ---------------------------
 *  心理测评答题记录Controller(PsyAnswerController)         
 * ---------------------------
 */
@RestController
@RequestMapping("psyAnswer")
public class PsyAnswerController {

    @Autowired
    private PsyAnswerService psyAnswerService;
    
    @Autowired
    private PsyQuestionService psyQuestionService;
    
    @Autowired
    private BusTermService busTermService;

    /**
     * 根据学生和学期查询答题记录
     * @param termId 学期ID
     * @return 答题记录
     */
    @GetMapping(value="/findByCurrentUser")
    public HttpResult findByCurrentUser(@RequestParam Long termId) {
        String studentNum = SecurityUtils.getUsername();
        List<PsyAnswer> answers = psyAnswerService.findByStudentAndTerm(studentNum, termId);
        
        // 如果没有答题记录，则返回该学期的所有题目（空答案）
        if (answers == null || answers.isEmpty()) {
            List<PsyQuestion> questions = psyQuestionService.findByTermId(termId);
            return HttpResult.ok(questions);
        }
        
        return HttpResult.ok(answers);
    }
    
    /**
     * 保存学生答题记录
     * @param answers 答题记录
     * @param termId 学期ID
     * @return 操作结果
     */
    @PostMapping(value="/saveAnswers")
    public HttpResult saveAnswers(@RequestBody List<PsyAnswer> answers, @RequestParam Long termId) {
        // 检查学期是否有效
        BusTerm busTerm = busTermService.findById(termId);
        if(ObjectUtils.isEmpty(busTerm) || !SysConstants.TERM_STATUS_2.equals(busTerm.getStatus())){
            return HttpResult.error("当前学期未开始或已结束");
        }
        
        // 获取当前学生学号
        String studentNum = SecurityUtils.getUsername();
        
        // 保存答题记录
        int count = psyAnswerService.saveAnswers(answers, studentNum, termId);
        
        return HttpResult.ok("成功保存 " + count + " 道题目的答案");
    }
    
    /**
     * 根据学生和学期查询答题记录（管理员用）
     * @param studentNum 学号
     * @param termId 学期ID
     * @return 答题记录
     */
    @GetMapping(value="/findByStudentAndTerm")
    public HttpResult findByStudentAndTerm(@RequestParam String studentNum, @RequestParam Long termId) {
        return HttpResult.ok(psyAnswerService.findByStudentAndTerm(studentNum, termId));
    }
} 